﻿using NHibernate;
using PAP.Application.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PAP.Infrastructure.DataAccess.NH.Domain
{
    public class NHUnitOfWork : IUnitOfWork<ISession>
    {
        #region "Fields"
        private readonly ITransaction _transaction;
        #endregion

        #region "Constructors"
        public NHUnitOfWork(ISessionFactory sessionFactory)
            : base()
        {
            Context = sessionFactory.OpenSession();
            _transaction = Context.BeginTransaction(IsolationLevel.ReadCommitted);
        }
        #endregion

        #region "Properties"
        public ISession Context
        {
            get;
            private set;
        }
        #endregion

        #region "Methods"
        public void Commit()
        {
            if (!this._transaction.IsActive)
            {
                throw new InvalidOperationException("Transakcja nie jest aktywna!");
            }

            this._transaction.Commit();
        }

        public void Rollback()
        {
            if (this._transaction.IsActive)
            {
                this._transaction.Rollback();
            }
        }

        public void Dispose()
        {
            // TODO
        }
        #endregion
    }
}
